package com.samphanie.admin.security;

import cn.hutool.core.util.ObjectUtil;
import com.samphanie.admin.modules.sys.service.ISysUserService;
import com.samphanie.common.execetion.ApiException;
import com.samphanie.mbg.model.sys.SysUser;
import com.samphanie.security.domain.SecurityUser;
import com.samphanie.security.security.service.UserDetailsExtensionService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * @author Dries
 */
@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsExtensionService {

    private final ISysUserService adminUserService;

    /**
     * 根据账户登录
     * @param username 账户
     * @return UserDetails
     * @throws UsernameNotFoundException 抛异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = adminUserService.findUserByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Cannot find user"));
        return SecurityUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .enabled(user.isEnabled())
                .accountNonExpired(user.isAccountNonExpired())
                .accountNonLocked(user.isAccountNonLocked())
                .credentialsNonExpired(user.isCredentialsNonExpired())
                .authorities(user.getRoles().stream()
                        .map(role -> new SimpleGrantedAuthority(role.getRoleName()))
                        .collect(Collectors.toSet())
                ).build();
    }

    /**
     * 根据手机号登录
     *
     * @param mobile 手机号
     * @return UserDetails
     * @throws UsernameNotFoundException 抛异常
     */
    @Override
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        throw new UsernameNotFoundException("暂不支持的手机号一键登录方式");
    }

    /**
     * 根据社交账号登录
     *
     * @param openId 第三方的绑定的openId
     * @return UserDetails
     * @throws UsernameNotFoundException 抛异常
     */
    @Override
    public UserDetails loadUserBySocial(String openId) throws UsernameNotFoundException {
        throw new UsernameNotFoundException("暂不支持的社交登录方式");
    }
}
